/**
 *  This file is part of MunchLevel.
 *
 *  MunchLevel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MunchLevel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MunchLevel.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.munchlevel.view.adapter;

import android.content.Context;
import android.support.v4.app.FragmentManager;

import com.gandulf.guilib.view.adapter.MultiFragmentPagerAdapter;
import com.munchlevel.data.GameInfo;
import com.munchlevel.fragment.PlayerFragment;
import com.munchlevel.view.listener.OnPlayerChangedListener;

/**
 * @author Ganymede
 * 
 */
public class MultiPlayerPagerAdapter extends MultiFragmentPagerAdapter {

	protected GameInfo gameInfo;

	private OnPlayerChangedListener onPlayerChangedListener;

	private PlayerFragment[] mFragments;

	private int viewsPerPage;

	public MultiPlayerPagerAdapter(Context context, int viewsPerPage, FragmentManager fm, GameInfo gameInfo) {
		super(context, fm);

		this.gameInfo = gameInfo;
		this.mFragments = new PlayerFragment[gameInfo.getPlayers()];
		this.viewsPerPage = viewsPerPage;
	}

	public PlayerFragment getItem(int position) {
		PlayerFragment fragment = null;

		if (position < mFragments.length) {
			fragment = mFragments[position];

			if (fragment == null) {
				fragment = new PlayerFragment(gameInfo.getPlayer(position), gameInfo.getPlayers() < 2);
				fragment.setOnPlayerChangedListener(onPlayerChangedListener);
				mFragments[position] = fragment;
			}
		}
		return fragment;
	}

	public PlayerFragment getItem(int position, int tab) {
		int index = getStartIndex(position) + tab - 1;
		return getItem(index);
	}

	@Override
	public int getCount() {
		return (int) Math.ceil(gameInfo.getPlayers() / (float) viewsPerPage);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.munchlevel.view.adapter.MultiFragmentPagerAdapter#getCount(int)
	 */
	@Override
	public int getCount(int position) {
		return viewsPerPage;
	}

	public OnPlayerChangedListener getOnPlayerChangedListener() {
		return onPlayerChangedListener;
	}

	public void setOnPlayerChangedListener(OnPlayerChangedListener onPlayerChangedListener) {
		this.onPlayerChangedListener = onPlayerChangedListener;
	}

	public GameInfo getGameInfo() {
		return gameInfo;
	}

	public void setGameInfo(GameInfo gameInfo) {
		this.gameInfo = gameInfo;
		this.mFragments = new PlayerFragment[gameInfo.getPlayers()];

		notifyDataSetChanged();
	}

}
